/** 
Copyright (c) 2010, Sheikh Abdul Wahid Ahmed
Details @ http://extremecodeworld.codeplex.com/license
**/

using System;
using System.Data;
using System.Text;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using EXtremecode.PresentationLayer;
using EXtremecode.BusinessLayer;

public partial class ASCXCheckBoxList : System.Web.UI.UserControl, IListControl
{
    private bool isSetDisplayMethodCalled = false;
    private string returnListFormat = "{0}";
    protected void Page_Load(object sender, EventArgs e)
    {
        
    }
    public override string ClientID
    {
        get
        {
            return CurrentClientId;
        }
    }
    protected void Page_PreRender(object sender, EventArgs e)
    {
        vldrRequired.ErrorMessage = string.Format("{0} : {1}",
            caption,ResourceProvider.GetGeneralResourceString("Message_FieldRequired"));
        vldrRequired.Attributes.Add("ListToValidate", checkBoxList.ClientID);

       
        //Script block
        string currentClientId = this.CurrentClientId;
        string originalClientId = this.OriginalClientId;
        string inputClientId = this.InputClientId;
        string displayClientId = this.DisplayClientId;

        StringBuilder sbScriptBlock = new StringBuilder();

        sbScriptBlock.AppendLine("<script>");
        sbScriptBlock.AppendLine(
            string.Format("var {0} = document.getElementById('{0}');", currentClientId));

        sbScriptBlock.AppendLine(
            string.Format("{0}.OriginalCtrl = document.getElementById('{1}');",
                currentClientId, originalClientId));

        if (!IsReadOnly && checkBoxList.Items.Count >0 )
        {
            sbScriptBlock.AppendLine(
                string.Format("var {0} = document.getElementById('{0}');", inputClientId));

            sbScriptBlock.AppendLine(
               string.Format("{0}.CurrentCtrl = document.getElementById('{1}');",
                   inputClientId, currentClientId));
        }

        sbScriptBlock.AppendLine(
            string.Format("{0}.InputCtrl = document.getElementById('{1}');",
            currentClientId, inputClientId));

        sbScriptBlock.AppendLine(
            string.Format("{0}.DisplayCtrl = document.getElementById('{1}');",
            currentClientId, displayClientId));

        sbScriptBlock.AppendLine(
            string.Format("{0}.CheckBoxIdsSuffixWithValues = new Object();",
            currentClientId));

        sbScriptBlock.AppendLine(
            string.Format("{0}.Values = new Array({1});",
            currentClientId,checkBoxList.Items.Count));

        for (int i = 0; i < checkBoxList.Items.Count; i++)
        {
            ListItem lItem = checkBoxList.Items[i];
            sbScriptBlock.AppendLine(
                string.Format("{0}.CheckBoxIdsSuffixWithValues['{1}'] = '_{2}';",
                currentClientId, lItem.Value, i));

            sbScriptBlock.AppendLine(
                string.Format("{0}.Values[{1}] = '{2}';",
                currentClientId,i, lItem.Value));

        }

        sbScriptBlock.AppendLine(
            string.Format("{0}.SetValue = SetCheckListValue;", currentClientId));

        sbScriptBlock.AppendLine(
            string.Format("{0}.GetValue = GetCheckListValue;", currentClientId));

        sbScriptBlock.AppendLine(
            string.Format("{0}.ResetValue = resetValue;", currentClientId));


        sbScriptBlock.AppendLine("</script>");

        scriptBlockLiteral.Text = sbScriptBlock.ToString();


        if (!isSetDisplayMethodCalled)
        {
            SetDisplay();
        }

    }

    private void SetDisplay()
    {
        if (IsReadOnly)
        {
            bulletedList.Items.Clear();
            foreach (ListItem lItem in checkBoxList.Items)
            {
                if (lItem.Selected)
                {
                    bulletedList.Items.Add(lItem);
                }
            }
        }
    }
    public string ReturnListFormat
    {
        get
        {
            return returnListFormat;
        }
        set
        {
            returnListFormat = value;
        }
    }


#region IListControl Members
    
    private string[] displayFieldList;
    public string[] DisplayFieldList
    {
        get
        {
            return displayFieldList; 
        }
        set
        {
            displayFieldList = value;
        }
    }

    private IEnumerable enumerable;
    public IEnumerable Enumerable
    {
        get
        {
            return enumerable;
        }
        set
        {
            enumerable=value;
        }
    }

    private string formatString;
    public string FormatString
    {
        get
        {
            return formatString;
        }
        set
        {
            formatString=value;
        }
    }

    private string keyField;
    public string KeyField
    {
        get
        {
            return keyField;
        }
        set
        {
            keyField = value;
        }
    }

    public new void DataBind()
    {
        checkBoxList.Items.Clear();
        if (enumerable is BusinessObjectCollection)
        {
            try
            {
                BusinessObjectCollection boCol = (BusinessObjectCollection)enumerable;
                boCol.SortedBy = string.Join(",", displayFieldList);
                foreach (BusinessObjectPaper boPaper in boCol.GetBOPapers())
                {
                    ListItem lItem = new ListItem();
                    lItem.Value = Convert.ToString(boPaper[keyField]).Trim();

                    object[] displayFieldsValues = new object[displayFieldList.Length];
                    for (int i = 0; i < displayFieldList.Length; i++)
                    {
                        object val = boPaper[displayFieldList[i]];
                        displayFieldsValues[i] = (val != null) ? val : string.Empty;
                    }

                    lItem.Text = string.Format(formatString, displayFieldsValues);
                    checkBoxList.Items.Add(lItem);
                }
            }
            finally
            {
                ((BusinessObjectCollection)enumerable).Close();        
            }
        }
    }

    #endregion

#region IASCXControl Members

    public string DisplayCssClass
    {
        get
        {
            return bulletedList.CssClass;
        }
        set
        {
            bulletedList.CssClass = value;
        }
    }

    private bool isReadOnly = false;
    public bool IsReadOnly
    {
        get
        {
            return isReadOnly;
        }
        set
        {
            isReadOnly = value;
            if (isReadOnly)
            {
                multiView.SetActiveView(viewReadOnly);
            }
            else
            {
                multiView.SetActiveView(viewEditable);
            }
        }
    }

    public object OriginalValue
    {
        get
        {
            return hdnOriginal.Value; 
        }
    }
    public object Value
    {
        get
        {
            string str = string.Empty;
            string qoma = string.Empty;
            foreach (ListItem litem in checkBoxList.Items)
            {
                if (litem.Selected)
                {
                    str += qoma + string.Format(returnListFormat, litem.Value);
                    qoma = ",";
                }
            }
            return str;

        }
        set
        {
            try
            {
                if (value is string)
                {
                    value = ((string)value).Split(',');
                }

                if (value is Array)
                {
                    //uncheck all items and clear bulleted list first.
                    checkBoxList.ClearSelection();
                    bulletedList.Items.Clear();
                    string qoma = string.Empty;
                    string concatinatedList = string.Empty;
                    foreach (string str in (value as Array))
                    {
                        ListItem lItem = checkBoxList.Items.FindByValue(str.Trim());
                        if (lItem != null)
                        {
                            lItem.Selected = true;
                            concatinatedList += qoma + str;
                            qoma = ",";
                        }
                    }
                    hdnCurrent.Value = hdnOriginal.Value = concatinatedList;
                }


                SetDisplay();
                isSetDisplayMethodCalled = true;


            }
            finally
            {
            }
        }
    }
    public bool HasValueChanged
    {
        get
        {
            return (Value != OriginalValue);
        }
    }
    
    public string Text
    {
        get
        {
            string str = string.Empty;
            string qoma = string.Empty;
            foreach (ListItem litem in checkBoxList.Items)
            {
                if (litem.Selected)
                {
                    str +=  qoma + string.Format(returnListFormat,litem.Text);
                    qoma = ",";
                }
            }
            return str; 
        }
    }
    
    public string InputClientId
    {
        get
        {
            return checkBoxList.ClientID;
        }
    }
    public string InputUniqueId
    {
        get
        {
            return checkBoxList.UniqueID;
        }
    }
    
    public string DisplayClientId
    {
        get
        {
            return bulletedList.ClientID;
        }
    }
    public string DisplayUniqueId
    {
        get
        {
            return bulletedList.UniqueID;
        }
    }
    
    public string OriginalClientId
    {
        get
        {
            return hdnOriginal.ClientID;
        }
    }

    public string CurrentClientId
    {
        get
        {
            return hdnCurrent.ClientID;
        }
    }
    
    public Control InputControl
    {
        get
        {
            return checkBoxList;
        }
    }

    public string JSResetFunction
    {
        get
        {
            return "ResetCheckBoxList";
        }
    }
    
    private bool isRequired = false;
    public bool IsRequired
    {
        get
        {
            return isRequired;
        }
        set
        {
            isRequired = value;
            
            if (isRequired)
            {
                checkBoxList.CssClass = "requiredField";
                vldrRequired.Enabled = true;
                vldrRequired.Display = ValidatorDisplay.Dynamic; 
            }
            else
            {
                checkBoxList.CssClass = "";
                vldrRequired.Enabled = false;
                vldrRequired.Display = ValidatorDisplay.None;
            }
        }
    }

    private string caption=string.Empty;
    public string Caption
    {
        get
        {
            return caption;
        }
        set
        {
            caption = value;
        }
    }



    #endregion

 
}
